//
//  XGVideoViewController.swift
//  TodayNews
//
//  Created by monkey on 2020/2/3.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import JXSegmentedView
import AVKit

class XGVideoViewController: XGBaseListContainerViewController
{
    override func loadCategories(completion: @escaping ([String]) -> Void)
    {
        viewModel.fetchVideoCategories { (isSuccess) in
            if (isSuccess) {
                let titles = self.viewModel.videoCategories.compactMap({ return $0.name })
                completion(titles)
            }
        }
    }
    
    private let viewModel = XGVideoViewModel()
}

// MARK: - JXSegmentedListContainerViewDataSource

extension XGVideoViewController
{
    override func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int
    {
        return viewModel.videoCategories.count
    }
    
    override func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate
    {
        let newsListTableViewController = XGNewsListTableViewController(newsCategory: viewModel.videoCategories[index])
        newsListTableViewController.newsDelegate = self
        return newsListTableViewController
    }
}

// MARK: - XGNewsListTableViewControllerDelegate

extension XGVideoViewController: XGNewsListTableViewControllerDelegate
{
    func newsDidSelected(newsViewModel: XGNewsViewModel)
    {
        guard let videoId = newsViewModel.videoId else {
            return
        }
        
        viewModel.fetchVideoInfo(videoId: videoId) { (isSuccess, videoInfo) in
            guard isSuccess, let url = videoInfo?.videoUrl else {
                return
            }
            
            let viewController = XGVideoPlayerViewController(playVideoUrl: url)
            self.navigationController?.pushViewController(viewController, animated: true)
        }
    }
}
